from flask import Flask, request, jsonify, send_file
import os
import pandas as pd
import csv
app = Flask(__name__)

# Dummy data with sensitive information in a CSV file
sensitive_data_path = 'sensitive_data.csv'

# Populate sensitive_data.csv with dummy data
if not os.path.exists(sensitive_data_path):
    with open(sensitive_data_path, 'w') as f:
        writer = csv.writer(f)
        writer.writerow(["id", "name", "email", "credit_card", "auth_token"])
        for i in range(1, 100):
            writer.writerow([
                i, f"User_{i}", f"user{i}@example.com",
                f"{i*1000}-{i*1001}-{i*1002}-{i*1003}",
                f"{hex(i*10000000000)[2:]}"
            ])

# Vulnerable endpoint exposing user data without authorization
@app.route('/users', methods=['GET'])
def get_users():
    return jsonify(pd.read_csv(sensitive_data_path).to_dict(orient="records"))

# Login endpoint vulnerable to SQL injection
@app.route('/login', methods=['POST'])
def login():
    username = request.json.get("username", "")
    password = request.json.get("password", "")
    # Simulate SQL injection by using user-supplied data without sanitization
    if username == "admin" and password == "admin123":
        return jsonify({"message": "Login successful!"})
    return jsonify({"message": "Invalid credentials!"}), 401

# Endpoint with inadequate authorization for user profiles
@app.route('/profile/<int:user_id>', methods=['GET'])
def get_profile(user_id):
    # No explicit authorization check for viewing profiles
    df = pd.read_csv(sensitive_data_path)
    user = df[df['id'] == user_id]
    if not user.empty:
        return jsonify(user.iloc[0].to_dict())
    return jsonify({"message": "User not found"}), 404

# Endpoint for downloading sensitive data with a simple token
@app.route('/get_sensitive_data', methods=['GET'])
def get_sensitive_data():
    # Simple token-based authorization
    token = request.headers.get('Authorization', '')
    # Vulnerable due to predictable token
    if token == '12345':
        return send_file(
            sensitive_data_path,
            mimetype='text/csv',
            as_attachment=True
        )
    else:
        return jsonify({"message": "Unauthorized"}), 401

# Endpoint with verbose error messages
@app.route('/cause_error', methods=['GET'])
def cause_error():
    # Trigger an error to simulate verbose error messages
    return 1 / 0  # Division by zero error
if __name__ == '__main__':
    app.run(debug=True)
